<template>
    <view class="mkbody">
        <view class="mkboxbanner" v-if="!mkstart" :style="'background-image: url(http://hlj.offcn.com/zg/xiaochengxu/images/skmkbanner.jpg)'">
            <view class="mkboxbannertext">
                <view v-if="mkend" class="mkresult">
                    <h3>答题结果</h3>
                    <view class="mkresult_fenshu">
                        <strong class="red">{{userzdjl.fenshu}}</strong>
                        <view>得分</view>
                    </view>
                    <view class="mkresult_list mgbt15">
                        <!-- <p class="p2">当前排名： <span class="red">第 {{userzdjl.dqpaiming}} 名</span></p> -->
                        <p class="p_time">共计用时: <span class="red">{{userzdjl.examtime}}</span></p>
                        <p class="p2">正确率： <span class="red">{{( (userzdjl.fenshu/answerlist.length)*100).toFixed(2) + '%' }}</span></p>
                        <p class="p2">共计： <span>{{answerlist.length}}题</span></p>
                    </view>
                    <u-button name="notyz" plain type="info" class="mkbutton" @click="getmkSee">&nbsp;&nbsp;&nbsp;&nbsp;查看作答记录&nbsp;&nbsp;&nbsp;&nbsp;</u-button>
                </view>
                <u-button v-else name="notyz" plain type="primary" class="mkbutton" @click="getData">&nbsp;&nbsp;&nbsp;&nbsp;开始模考&nbsp;&nbsp;&nbsp;&nbsp;</u-button>
            </view>
        </view>

        <view class="mkbox fixed" v-else>
            <view class="jiaojuanbox" v-if="jiaojuan">
				<u-loading-icon mode="semicircle" text="提交中..." color="#1989fa" v-if="loading"></u-loading-icon>
                <view class="tipbox" v-else>
                    <!-- <u-icon name="checkmark-circle" size="100px" class="green" /> -->
                    <h3>提交成功</h3>
                    <u-button name="notyz" plain type="primary" @click="winreload">返回查看</u-button>
                </view>
            </view>
            <view v-else>
				<view class="mkinfobox">
					<view class="mkinfo">答题进度： <u-line-progress :percentage="progress" activeColor="#f44" style="margin-left: 20px;"></u-line-progress></view>
					<view class="mkinfo infoa">
						<view style="min-width: 60%;">
							<view v-if="!mkend" style="display: flex;">
								<span><u-icon name="clock"  /></span>{{'已用时： ' + mkexamtime}}
							</view>
						</view>
						<view><u-button type="info" round size="small" @click="examdtk">作答记录</u-button></view>
						<view v-if="!mkend"><u-button type="warning" round size="small" @click="submitexam">交卷</u-button></view>
					</view>
				</view>
				<div class="dtswiperbox" v-if="mkend">
					<swiper class="dtswiper" :style="{height: swiperheight + 'px'}" ref="dtswiper" :current="current" :vertical="false" :indicator-dots="false" @change="swiperchange">
						<block v-for="(data,dindex) in datalist" :key="dindex">
							<swiper-item class="dtitem" :class="{'active': current == dindex}">
								<mktopicend :class="'dtswiperitem'+dindex" :ksdata="data" :answerdata="answerlist[dindex]" :mkend="mkend"></mktopicend>
							</swiper-item>
						</block>
					</swiper>
				</div>
				<div class="dtswiperbox" v-else>
					<swiper class="dtswiper" :style="{height: swiperheight + 'px'}" ref="dtswiper" :current="current" :vertical="false" :indicator-dots="false" @change="swiperchange">
						<block v-for="(data,dindex) in datalist" :key="dindex">
							<swiper-item class="dtitem" :class="{'active': current == dindex}">
								<mktopic :class="'dtswiperitem'+dindex" :ksdata="data" :mkend="mkend" @rowselect="rowsel"></mktopic>
							</swiper-item>
						</block>
					</swiper>
				</div>
		
                <view style="height: 50px;"></view>
				<div class="dtcontrol">
					<u-row justify="space-between" gutter="10">
						<u-col span="6"><u-button type="primary" :plain="true" class="btn" @click.stop="tmprev">上一题</u-button></u-col>
						<u-col span="6"><u-button type="primary" class="btn" @click.stop="tmnext">下一题</u-button></u-col>
					</u-row>
				</div>
            </view>
        </view>

        <u-popup :show="ansermodel" mode="bottom" @close="dtkCancel">
            <dtk v-if="ansermodel" :tmNum="datalist.length" :answerlist="answerlist" :mkend=mkend @swipego="swiperJump"></dtk>
        </u-popup>
		<u-toast ref="uToast"></u-toast>
		<u-modal :show="showModal" :title="modelTlt" :content='modelContent' @confirm="commitexam" :showCancelButton="true" @cancel="showModal = false" :closeOnClickOverlay="true"></u-modal>
		
    </view>
</template>

<script>
	const db = wx.cloud.database()
	import {
		mapActions
	} from 'vuex';
    import mktopic from '@/components/mktopic';
    import mktopicend from '@/components/mktopicend';
    import dtk from './dtk';
	
    export default {
        name: "hd-gjgwy-2020gkmk",
        data () {
            return {
				name: '',
				hdInfo: {
					fucname: '',
					link: ''
				},
                datalist: [],
                answerlist:[],
                mkend: false,
                mkstart: false,
                ansermodel: false,
                jiaojuan: false,
                mkexamtime: '00:00:00',
                fenshu: 0,
                dqpaiming: 0,
                mkexamseconds: 0,
                mkexamtimeMAX: 7200,
                current: 0,
                loading: false,
                finished: false,
                userzdjl: {},
                limits: 300,
				swiperheight: 100,
				examtimer: null,
				showModal: false,
				modelTlt: "提示",
				modelContent: "提示信息",
				openid: ""
            }
        },
        created () {
            
        },
		
		onShareAppMessage(options) {
			let shareObj = {
			    title: "上岸数据助手-模考",
			    path: '/pages/huodong/mokao/index?name=' + this.name + "&fucname=" + this.fucname,
			    imageUrl: ''   
			};
			return shareObj
		},
		onShareTimeline(res) {
			let that = this;
			return {
				title: '上岸数据助手-模考',
				query: "name=" + that.name + "&fucname=" + that.fucname
			};
		},
        computed: {
            userdata(){
                return this.$store.getters.userdata ? this.$store.getters.userdata : ''
            },
            userphone(){
                return this.$store.getters.userphone ? this.$store.getters.userphone : ''
            },
			username() {
				return this.$store.getters.username ? this.$store.getters.username : '';
			},
            progress(){
                var arr = []
                if (this.mkend) {
                    this.answerlist.filter(item => {if (item.an != '') arr.push(item.an)})
                }else{
                    this.answerlist.filter(item => {if (item != '') arr.push(item)})
                }
                return Math.round(arr.length / this.answerlist.length * 10000) / 100.00
            }
        },
		mounted(){
			this.name = this.name ? this.name : this.username;
			this.LogSetName(this.name);
			this.getUserInfo()
			this.getopenid()
		},
		onLoad(options){
			if (!options) {} else {
				this.name = options.name
				this.hdInfo.fucname = options.fucname
				this.hdInfo.link = 'https://www.baixuemianshi.com/zhuanti/mokao/' + options.fucname + '/index.js'
				
			}
		},
        methods: {
			...mapActions(['LogSetName']),
			getopenid() {
				let that = this;
				wx.cloud.callFunction({
					name: 'getopenid',
					data: {},
					complete: res => {
						that.openid = res.result.openid
						that.getuserzdjl()
					}
				});
			},
			async getUserInfo(){
				const udInfo = await this.$getUser.getInfo(this.name)
				// this.userInfo.ewm = udInfo.ewm1
				
			},
			initheight(){
				var that = this
				var query = wx.createSelectorQuery();
				query.selectAll('.dtswiperitem0').boundingClientRect()
				query.exec((res) => {
					var listHeight = res[0][0].height; // 获取list高度
					that.swiperheight = listHeight + 60
					wx.hideLoading()
				})
			},
            getuserzdjl(){
                var that = this
				
				db.collection(that.hdInfo.fucname).where({
					openid: that.openid
				})
				.get({
					success: function(res){
						console.log('success: ', res)
						if(res.data.length > 0){
							that.userzdjl = res.data[0]
							that.userzdjl.answer.split('/').forEach((it,ind) => {
							  	that.answerlist.push({ an: it, st: null })
							})
							that.mkend = true
							
						}
					},
					fail: function(res){
						console.log('fail: ', res)
					}
				})
            },
            getmkSee(){
				var that = this
				wx.showLoading({ title: "加载中", mask: true })
                that.mkstart = true
                that.jiaojuan = false
				that.getData()
				
            },
            getData(){  //获取题目
                var that = this
				uni.request({
				    url: that.hdInfo.link ,
				    method: 'get',
				    dataType: 'text',
				    data: { sstimes: new Date()},
				    success: function (res) {
				        var resjson = JSON.parse(res.data);
				        that.datalist = resjson
						that.datalist = resjson.filter((item,pi) => {
							if (!that.mkend) {
								that.answerlist[item.id - 1] = ''
							}else{
								that.answerlist.forEach((it,ind) => {
									if (pi == ind){
										if (it.an == '') return
										if (it.an == item.correct){it.st = 1} else {it.st = 2}
									}
								})
								setTimeout((it)=>{
									that.initheight()
								},200)
							}
							return item
						})
						that.examstart()
				    }
				})
                

            },
            examstart(){   //开始考试
				var	that = this
				wx.showLoading({ title: "加载中", mask: true })
                that.mkstart = true
                that.selectTime()
				setTimeout((it)=>{
					that.initheight()
				},200)
            },
            submitexam(){   //交卷
                var that = this
				
				let noexarr = that.answerlist.filter(item => item == '')
                if (noexarr.length > 0){
					that.modelContent = '您还有' + noexarr.length + '道题未作答，确定要交卷吗？'
					that.showModal = true
                }else{
                    that.modelContent = '确定要交卷吗？'
					that.showModal = true
                }
            },
            commitexam(){
                var that = this
                that.loading = true
                that.jiaojuan = true
                that.mkend = true
				that.showModal = false
                var defen = 0
                //点击确定
                that.datalist.forEach((item,pi) => {
                    that.answerlist.forEach((it,ind) => {
                        if (pi == ind){if (it == item.correct){ defen += item.score * 1 }}
                    })
                })
				
				
				db.collection(that.hdInfo.fucname).add({
				    data: {
						openid: that.openid,
						user: that.name,
						remark: that.hdInfo.mkname,
						examtime: that.mkexamtime,
						fenshu: defen,
						answer: that.answerlist.join('/'),
						time: new Date()
				    },
					success: function(res) {
					    that.loading = false
					    setTimeout(() => {
					        that.winreload()
					    },3000)
					}
				})
            },
            winreload(){
                this.datalist = []
                this.answerlist = []
                this.mkend= false
                this.mkstart= false
                this.ansermodel= false
                this.jiaojuan= false
                this.mkexamtime= '00:00:00'
                this.fenshu= 0
                this.dqpaiming= 0
                this.mkexamseconds= 0
                this.mkexamtimeMAX= 7200
                this.current= 0
                this.loading= false
                this.finished= false
                this.userzdjl= {}
                this.limits= 300
                this.swiperheight= 100
				this.getuserzdjl()
            },
            examdtk(){
                this.ansermodel = true
            },
            dtkCancel(){
                this.ansermodel = false
            },
            secondToDate(result){
                var h = Math.floor(result / 3600) < 10 ? '0' + Math.floor(result / 3600) : Math.floor(result / 3600);
                var m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60));
                var s = Math.floor((result % 60)) < 10 ? '0' + Math.floor((result % 60)) : Math.floor((result % 60));
                this.mkexamtime = h + ":" + m + ":" + s
            },
            selectTime(){
                var that = this
                if (that.mkexamseconds >= that.mkexamtimeMAX) {
                    // Toast('作答时间到')
					that.showToast('default','作答时间到')
                    that.commitexam()
                }
                that.secondToDate(that.mkexamseconds)
                if(that.mkend) return;
                that.mkexamseconds++
				that.examtimer = setTimeout(() => {
					that.selectTime()
				},1000)
            },
            rowsel(tid,tstatus,tselectans){
                var that = this
                that.answerlist.splice((tid - 1), 1, tselectans.join(''))
            },
            tmprev(){
                if (this.current == 0){
					// Toast('已经是第一题了');
					return
				}
                this.current -= 1
                this.swiperJump(this.current)
            },
            tmnext(){
                if (this.current == this.datalist.length-1){
					// Toast('已经是最后一题了');
					this.submitexam()
					return
				}
                this.current += 1
                this.swiperJump(this.current)
            },
            swiperchange(event){
				var that = this
                that.current = event.detail.current
				var query = wx.createSelectorQuery();
				query.selectAll('.dtswiperitem' + event.detail.current).boundingClientRect()
				query.exec((res) => {
					// console.log(res)
					var listHeight = res[0][0].height; // 获取list高度
					that.swiperheight = listHeight + 60
				})
            },
            swiperJump(index){
				this.current = index
                this.dtkCancel()
            },
			showToast(type, info) {
				this.$refs.uToast.show({
					type: type,
					icon: false,
					title: '失败主题',
					message: info,
				})
			},
        },
		beforeDestroy() {
		    clearInterval(this.examtimer);
			this.examtimer = null;
			this.winreload()
		},
        components:{
            mktopic, dtk, mktopicend
        }
    };
</script>

<style>
	@import url(./index.css);
</style>